<script lang="ts" setup>
import { onBeforeUnmount, onMounted, ref, nextTick } from 'vue'
import { echarts } from '../../utils'
import ComCard from './Card.vue'

const chartRef = ref<echarts.ECharts>()
const chartDomRef = ref()

const renderChart = (data?: any) => {
  if (!chartRef.value) {
    chartRef.value = echarts.init(chartDomRef.value)
  }
  chartRef.value.setOption({
    title: {
      text: '网关实时TPS',
      subtext: '0',
      textStyle: {
        fontSize: 13,
        color: '#909399',
        lineHeight: 20
      },
      subtextStyle: {
        fontSize: 30,
        color: '#303133'
      },
      textAlign: 'center',
      left: '50%',
      top: '42%'
    },
    series: [
      {
        name: 'flow rate',
        type: 'pie',
        radius: ['50%', '70%'],
        color: ['rgb(110, 218, 218)', 'rgb(58, 160, 255)'],
        label: {
          formatter: '{b}: {c}'
        },
        title: {
          offsetCenter: [0, '-10%'],
          fontSize: 20
        },
        data: [
          { value: 8, name: '累计失败次数' },
          { value: 2900, name: '累计调用次数' }
        ]
      }
    ]
  })
}

const onResize = () => {
  if (chartRef.value) {
    chartRef.value.resize()
  }
}

const onUnmount = () => {
  if (chartRef.value) {
    chartRef.value.dispose()
    chartRef.value = null
  }
  window.removeEventListener('resize', onResize)
}

onMounted(async () => {
  await nextTick()
  renderChart()
  window.addEventListener('resize', onResize)
})

onBeforeUnmount(onUnmount)
</script>

<template>
  <ComCard title="网关实时流量">
    <div ref="chartDomRef"></div>
  </ComCard>
</template>
